package com.foftact.block;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 板块数据控制器
 */
@Controller
@RequestMapping("/block")
public class BlockController {

    private static final Logger logger = LoggerFactory.getLogger(BlockController.class);

    @Autowired
    private BlockService blockService;

    /**
     * 跳转到板块数据列表页面
     */
    @GetMapping("/list")
    public String listPage() {
        return "block/list";
    }

    /**
     * 异步获取板块数据列表
     */
    @GetMapping("/dataList")
    @ResponseBody
    public List<Block> getDataList() {
        logger.info("获取板块数据列表");
        return blockService.getAllBlocks();
    }

    /**
     * 手动触发数据抓取
     */
    @GetMapping("/fetchData")
    @ResponseBody
    public Map<String, Object> fetchData() {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("手动触发板块数据抓取");
            int count = blockService.fetchAndSaveBlockData();
            result.put("success", true);
            result.put("message", "数据抓取成功，新增/更新数据：" + count + " 条");
        } catch (Exception e) {
            logger.error("手动触发数据抓取失败", e);
            result.put("success", false);
            result.put("message", "数据抓取失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据代码获取板块详情
     */
    @GetMapping("/detail/{code}")
    @ResponseBody
    public Map<String, Object> getDetail(@PathVariable("code") String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            Block block = blockService.getBlockByCode(code);
            if (block != null) {
                result.put("success", true);
                result.put("data", block);
            } else {
                result.put("success", false);
                result.put("message", "未找到板块数据");
            }
        } catch (Exception e) {
            logger.error("获取板块详情失败：{}", code, e);
            result.put("success", false);
            result.put("message", "获取板块详情失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 跳转到数据统计页面
     */
    @GetMapping("/statistics")
    public String statisticsPage(Model model) {
        try {
            List<Block> blocks = blockService.getAllBlocks();
            model.addAttribute("totalCount", blocks.size());
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            model.addAttribute("totalCount", 0);
        }
        return "block/statistics";
    }
}